# models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import gettext_lazy as _


# =============================
# 1. 用户表 (qb_users)
# =============================
class User(AbstractUser):
    """
    用户表：支持角色、登录状态、时间记录
    """

    # 覆盖默认字段以匹配 SQL
    username = models.CharField(_('username'), max_length=150, unique=True)
    password = models.CharField(_('password'), max_length=128)
    email = models.EmailField(_('email address'), unique=True, null=True, blank=True)
    full_name = models.CharField('姓名', max_length=100)

    ROLE_CHOICES = [
        ('admin', '管理员'),
        ('teacher', '教师'),
        ('editor', '编辑'),
    ]
    role = models.CharField('角色', max_length=20, choices=ROLE_CHOICES, default='teacher')

    is_active = models.BooleanField('是否启用', default=True)
    is_staff = models.BooleanField('是否可登录后台', default=False)
    date_joined = models.DateTimeField('注册时间', auto_now_add=True)
    last_login = models.DateTimeField('最后登录时间', blank=True, null=True)

    class Meta:
        db_table = 'qb_users'
        verbose_name = '用户'
        verbose_name_plural = '用户管理'
        indexes = [
            models.Index(fields=['username'], name='idx_username'),
            models.Index(fields=['email'], name='idx_email'),
            models.Index(fields=['role'], name='idx_role'),
        ]

    def __str__(self):
        return f"{self.full_name}({self.username})"


# =============================
# 2. 学科表 (qb_subjects) - 支持层级
# =============================
class Subject(models.Model):
    name = models.CharField('学科名称', max_length=100, help_text='如：数学、语文、英语')
    code = models.CharField('学科编码', max_length=20, unique=True, null=True, blank=True, help_text='如：MATH, CHINESE')

    LEVEL_CHOICES = [
        (1, '一级学科'),
        (2, '二级学科'),
    ]
    level = models.SmallIntegerField('学科层级', default=1, choices=LEVEL_CHOICES)

    parent = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True,
                               db_column='parent_id', verbose_name='父级学科')
    is_active = models.BooleanField('是否启用', default=True)
    sort_order = models.IntegerField('排序权重', default=0)

    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)

    class Meta:
        db_table = 'qb_subjects'
        verbose_name = '学科'
        verbose_name_plural = '学科管理'
        indexes = [
            models.Index(fields=['name'], name='idx_name'),
            models.Index(fields=['code'], name='idx_code'),
            models.Index(fields=['parent'], name='idx_parent_id'),
        ]

    def __str__(self):
        return self.name


# =============================
# 3. 标签表 (qb_tags)
# =============================
class Tag(models.Model):
    name = models.CharField('标签名称', max_length=50, help_text='如：函数、几何、易错题')
    category = models.CharField('标签分类', max_length=50, null=True, blank=True, help_text='如：知识点、难度、题型')
    description = models.TextField('标签说明', null=True, blank=True)
    used_count = models.IntegerField('被使用次数', default=0)

    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)

    class Meta:
        db_table = 'qb_tags'
        verbose_name = '标签'
        verbose_name_plural = '标签管理'
        unique_together = ('name', 'category')  # 对应 uk_name_category
        indexes = [
            models.Index(fields=['category'], name='idx_category'),
        ]

    def __str__(self):
        return f"{self.name}({self.category or '无分类'})"


# =============================
# 4. 试题表 (qb_questions)
# =============================
class Question(models.Model):
    QUESTION_TYPE_CHOICES = [
        ('single', '单选题'),
        ('multiple', '多选题'),
        ('true_false', '判断题'),
        ('short_answer', '简答题'),
        ('fill_blank', '填空题'),
    ]
    question_type = models.CharField('题型', max_length=20, choices=QUESTION_TYPE_CHOICES)

    title = models.TextField('题干内容', help_text='支持HTML或富文本')
    difficulty = models.SmallIntegerField('难度等级', default=3, help_text='1-5级，应用层校验')
    analysis = models.TextField('题目解析', null=True, blank=True)
    reference = models.CharField('来源/出处', max_length=200, null=True, blank=True, help_text='如：教材P10')

    subject = models.ForeignKey(Subject, on_delete=models.CASCADE, db_column='subject_id', verbose_name='所属学科')
    creator = models.ForeignKey(User, on_delete=models.CASCADE, db_column='creator_id', verbose_name='创建人')

    STATUS_CHOICES = [
        ('draft', '草稿'),
        ('reviewing', '审核中'),
        ('published', '已发布'),
        ('disabled', '已禁用'),
    ]
    status = models.CharField('状态', max_length=20, choices=STATUS_CHOICES, default='draft')

    view_count = models.IntegerField('浏览次数', default=0)
    use_count = models.IntegerField('被组卷使用次数', default=0)

    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)

    class Meta:
        db_table = 'qb_questions'
        verbose_name = '试题'
        verbose_name_plural = '试题管理'
        indexes = [
            models.Index(fields=['subject'], name='idx_subject_id'),
            models.Index(fields=['creator'], name='idx_creator_id'),
            models.Index(fields=['question_type'], name='idx_type'),
            models.Index(fields=['difficulty'], name='idx_difficulty'),
            models.Index(fields=['status'], name='idx_status'),
            models.Index(fields=['created_at'], name='idx_created_at'),
        ]

    def __str__(self):
        return f"{self.get_question_type_display()} - {self.title[:50]}..."


# =============================
# 5. 试题-标签关联表 (qb_question_tags)
# =============================
class QuestionTag(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE, db_column='question_id', verbose_name='试题')
    tag = models.ForeignKey(Tag, on_delete=models.CASCADE, db_column='tag_id', verbose_name='标签')
    created_at = models.DateTimeField('创建时间', auto_now_add=True)

    class Meta:
        db_table = 'qb_question_tags'
        verbose_name = '试题标签关联'
        verbose_name_plural = '试题标签管理'
        unique_together = ('question', 'tag')  # 对应 uk_question_tag
        indexes = [
            models.Index(fields=['tag'], name='idx_tag_id'),
        ]

    def __str__(self):
        return f"{self.question} -> {self.tag}"


# =============================
# 6. 试卷表 (qb_exam_papers)
# =============================
class ExamPaper(models.Model):
    title = models.CharField('试卷名称', max_length=200)
    description = models.TextField('试卷说明', null=True, blank=True)
    total_score = models.DecimalField('总分', max_digits=6, decimal_places=2, default=100.00)
    duration_minutes = models.IntegerField('考试时长（分钟）', default=90)
    difficulty = models.SmallIntegerField('难度等级', default=3, help_text='1-5级，应用层校验')

    creator = models.ForeignKey(User, on_delete=models.CASCADE, db_column='creator_id', verbose_name='创建人')
    subject = models.ForeignKey(Subject, on_delete=models.CASCADE, db_column='subject_id', verbose_name='所属学科')

    STATUS_CHOICES = [
        ('draft', '草稿'),
        ('published', '已发布'),
        ('archived', '已归档'),
    ]
    status = models.CharField('状态', max_length=20, choices=STATUS_CHOICES, default='draft')

    generated_from = models.JSONField('生成配置', null=True, blank=True, help_text='如：智能组卷参数（JSON）')

    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)

    class Meta:
        db_table = 'qb_exam_papers'
        verbose_name = '试卷'
        verbose_name_plural = '试卷管理'
        indexes = [
            models.Index(fields=['creator'], name='idx_creator_id'),
            models.Index(fields=['subject'], name='idx_subject_id'),
            models.Index(fields=['status'], name='idx_status'),
        ]

    def __str__(self):
        return self.title


# =============================
# 7. 试题导入日志表 (qb_import_logs)
# =============================
class ImportLog(models.Model):
    file_name = models.CharField('上传文件名', max_length=255)
    file_size = models.BigIntegerField('文件大小（字节）')
    total_count = models.IntegerField('总记录数', default=0)
    success_count = models.IntegerField('成功导入数', default=0)
    fail_count = models.IntegerField('失败数', default=0)
    error_log = models.TextField('错误详情', null=True, blank=True, help_text='JSON或文本')

    importer = models.ForeignKey(User, on_delete=models.CASCADE, db_column='importer_id', verbose_name='操作人')

    IMPORT_TYPE_CHOICES = [
        ('manual', '手动导入'),
        ('scheduled', '定时任务'),
    ]
    import_type = models.CharField('导入类型', max_length=20, choices=IMPORT_TYPE_CHOICES, default='manual')

    STATUS_CHOICES = [
        ('pending', '待处理'),
        ('processing', '处理中'),
        ('completed', '已完成'),
        ('failed', '失败'),
    ]
    status = models.CharField('状态', max_length=20, choices=STATUS_CHOICES, default='pending')

    started_at = models.DateTimeField('开始时间', null=True, blank=True)
    completed_at = models.DateTimeField('完成时间', null=True, blank=True)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)

    class Meta:
        db_table = 'qb_import_logs'
        verbose_name = '导入日志'
        verbose_name_plural = '导入日志管理'
        indexes = [
            models.Index(fields=['importer'], name='idx_importer_id'),
            models.Index(fields=['status'], name='idx_status'),
            models.Index(fields=['-created_at'], name='idx_created_at'),
        ]

    def __str__(self):
        return f"{self.file_name} - {self.get_status_display()}"


# =============================
# 8. 角色表（可选扩展，qb_roles）
# =============================
class Role(models.Model):
    name = models.CharField('角色名称', max_length=50, unique=True, help_text='如：管理员、教师、编辑')
    description = models.TextField('角色描述', null=True, blank=True)
    permissions = models.JSONField('权限列表', null=True, blank=True, help_text='JSON 格式权限配置')

    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)

    class Meta:
        db_table = 'qb_roles'
        verbose_name = '角色'
        verbose_name_plural = '角色管理'
        indexes = [
            models.Index(fields=['name'], name='idx_name'),
        ]

    def __str__(self):
        return self.name